#include "yk_comparison.h"
#include "ui_yk_comparison.h"
#include <QPushButton>
#include <QDateTime>
#include "state_group.h"
#include "dealer_handler.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include "database_manager.h"
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#include <QFile>
#include <QDebug>

YKComparison::YKComparison(SearchTreeWidget *search_tree, QWidget *parent)
    : QWidget(parent),
      ui_(new Ui::YKComparison),
      search_tree_(search_tree),
      dealer_handler_(DealerHandler::getInstance()),
      is_comparing_(false)
{
    // 注册YKItem类型
    qRegisterMetaType<YKItem>("YKItem");
    ui_->setupUi(this);

    // 设置日期时间格式
    ui_->startDTEdit->setDisplayFormat("yyyy-MM-dd HH:mm");

    // 连接按钮点击信号到槽函数
    connect(ui_->launchBtn, &QPushButton::clicked, this, &YKComparison::onLaunchBtnClicked);
    connect(dealer_handler_, &DealerHandler::messageReceived, this, &YKComparison::onNetworkMessageReceived);

    // ui->tableWidget表格列宽
    ui_->comparisonTable->setColumnWidth(0, 50);
    ui_->comparisonTable->setColumnWidth(1, 100);
    ui_->comparisonTable->setColumnWidth(2, 250);
    ui_->comparisonTable->setColumnWidth(3, 100);
    ui_->comparisonTable->setColumnWidth(4, 100);
    ui_->comparisonTable->setColumnWidth(7, 100);
    ui_->comparisonTable->setColumnWidth(9, 100);
    ui_->comparisonTable->setColumnWidth(10, 100);
    ui_->comparisonTable->setColumnWidth(13, 100);

    // 连接表格点击信号
    connect(ui_->comparisonTable, &QTableWidget::cellClicked, this, &YKComparison::onTableItemClicked);

    // ban export btn
    ui_->exportBtn->setEnabled(false);
}

YKComparison::~YKComparison()
{
    delete ui_;
}

void YKComparison::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    // 刷新ui_->startDTEdit
    ui_->startDTEdit->setDateTime(QDateTime::currentDateTime());

    // 清空下拉菜单
    ui_->d5000Combo->clear();
    ui_->generationCombo->clear();

    // 遍历所有主站组
    for (int i = 0; i < search_tree_->stateGroupVecSize(); i++)
    {
        StateGroup *group = search_tree_->stateGroupVec(i);
        if (!group)
        {
            continue;
        }

        // 获取该主站下的所有子站
        const QVector<StateInfo *> &child_states = group->stateInfosVec();

        // 添加到下拉菜单
        for (const auto &state : child_states)
        {
            if (!state)
            {
                continue;
            }

            // 创建显示文本
            QString display_text = state->stateName();

            // 创建用户数据，包含host和id
            QVariantMap user_data;
            user_data["host"] = state->host();
            user_data["id"] = QVariant::fromValue(state->id());

            // 添加到两个下拉菜单
            if (i == 0)
            {
                ui_->d5000Combo->addItem(display_text, QVariant(user_data));
            }
            if (i == 1)
            {
                ui_->generationCombo->addItem(display_text, QVariant(user_data));
            }
        }
    }

    // 从search_tree_获取两个主站的名字
    if (search_tree_->stateGroupVecSize() == 2)
    {
        StateGroup *state_group = search_tree_->stateGroupVec(0);
        QString station_name_1 = state_group->stateInfo()->description();
        ui_->subname_1_label->setText(station_name_1);
        ui_->subname_3_label->setText(station_name_1);

        state_group = search_tree_->stateGroupVec(1);
        QString station_name_2 = state_group->stateInfo()->description();
        ui_->subname_2_label->setText(station_name_2);
        ui_->subname_4_label->setText(station_name_2);
    }
}

void YKComparison::onLaunchBtnClicked()
{
    is_comparing_ = !is_comparing_;

    if (is_comparing_)
    {
        ui_->launchBtn->setText("停止对比");
        ui_->launchBtn->setProperty("isComparing", true);
        ui_->exportBtn->setEnabled(false);
    }
    else
    {
        ui_->launchBtn->setText("开始对比");
        ui_->launchBtn->setProperty("isComparing", false);
        ui_->exportBtn->setEnabled(true);
    }

    // 强制更新样式
    ui_->launchBtn->style()->unpolish(ui_->launchBtn);
    ui_->launchBtn->style()->polish(ui_->launchBtn);
    ui_->launchBtn->update();

    // 如果开始对比，则启动对比线程
    if (is_comparing_)
    {
        onStartComparison();
    }
}

void YKComparison::onStartComparison()
{
    // 获取两个下拉菜单的选中项
    QVariant d5000_item = ui_->d5000Combo->currentData();
    QVariant generation_item = ui_->generationCombo->currentData();

    if (d5000_item.isNull() || generation_item.isNull())
    {
        return;
    }

    // 获取选中项的host和id
    QString d5000_host = d5000_item.toMap()["host"].toString();
    QString generation_host = generation_item.toMap()["host"].toString();

    // 获取选中项的id
    int d5000_id = d5000_item.toMap()["id"].toInt();
    int generation_id = generation_item.toMap()["id"].toInt();

    // 获取开始时间
    QDateTime start_time = ui_->startDTEdit->dateTime();
    qint64 start_timestamp = start_time.toMSecsSinceEpoch();

    // 组装 JSON 数据
    QJsonObject json_obj;
    QJsonArray slave_stations;
    slave_stations.append(d5000_host);
    slave_stations.append(generation_host);
    json_obj["slaveStations"] = slave_stations;
    json_obj["timestamp"] = start_timestamp;

    QJsonDocument doc(json_obj);
    QString json_str = doc.toJson(QJsonDocument::Compact);

    dealer_handler_->sendRequest("select-yk-comparison", json_str);
}

void YKComparison::onNetworkMessageReceived(const QString &method, const QString &body)
{
    if (method == "select-yk-comparison")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (doc.isNull() || !doc.isObject())
        {
            return;
        }

        QJsonObject root = doc.object();
        if (!root.contains("itemsGroupBy"))
        {
            return;
        }

        QJsonObject itemsGroupBy = root["itemsGroupBy"].toObject();

        // 清空现有数据
        point_address_list_.clear();
        point_address_group_.clear();

        // 获取当前选中的host
        QVariant d5000_item = ui_->d5000Combo->currentData();
        QVariant generation_item = ui_->generationCombo->currentData();

        if (d5000_item.isNull() || generation_item.isNull())
        {
            return;
        }

        QString d5000_host = d5000_item.toMap()["host"].toString();
        QString generation_host = generation_item.toMap()["host"].toString();

        // 遍历itemsGroupBy中的所有键值对
        for (auto it = itemsGroupBy.begin(); it != itemsGroupBy.end(); ++it)
        {
            QString host = it.key();
            QJsonArray items = it.value().toArray();

            // 添加新的数据
            for (const QJsonValue &value : items)
            {
                if (value.isObject())
                {
                    QJsonObject obj = value.toObject();
                    YKItem item;
                    if (!point_address_list_.contains(obj["pointAddress"].toInt()))
                    {
                        point_address_list_.append(obj["pointAddress"].toInt());
                    }
                    item.commonAddress = obj["commonAddress"].toInt();
                    item.timestamp = obj["timestamp"].toVariant().toLongLong();
                    item.tieIdentificationIndex = obj["tieIdentificationIndex"].toInt();
                    item.tieIdentification = obj["tieIdentification"].toString();
                    item.causeIndex = obj["causeIndex"].toInt();
                    item.cause = obj["cause"].toString();
                    item.pointAddress = obj["pointAddress"].toInt();
                    item.value = obj["value"].toInt();
                    item.iv = obj["iv"].toInt();
                    item.direction = obj["direction"].toInt();
                    std::pair<QVector<YKItem>, QVector<YKItem>> &pair = point_address_group_[obj["pointAddress"].toInt()];
                    if (host == d5000_host)
                    {
                        pair.first.append(item);
                    }
                    else if (host == generation_host)
                    {
                        pair.second.append(item);
                    }
                }
            }
        }

        // 触发数据更新
        onDataUpdated();
    }

    if (method == "yk-comparison-publish")
    {
        if (!is_comparing_)
        {
            return;
        }

        QVariant d5000_item = ui_->d5000Combo->currentData();
        QVariant generation_item = ui_->generationCombo->currentData();

        if (d5000_item.isNull() || generation_item.isNull())
        {
            return;
        }

        // 获取选中项的host和id
        QString d5000_host = d5000_item.toMap()["host"].toString();
        QString generation_host = generation_item.toMap()["host"].toString();

        // 解析JSON响应
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (doc.isNull() || !doc.isObject())
        {
            return;
        }

        QJsonObject root = doc.object();
        if (!root.contains("itemsGroupBy"))
        {
            return;
        }

        QJsonObject itemsGroupBy = root["itemsGroupBy"].toObject();

        // 遍历itemsGroupBy中的所有键值对
        for (auto it = itemsGroupBy.begin(); it != itemsGroupBy.end(); ++it)
        {
            QString host = it.key();
            QJsonArray items = it.value().toArray();

            // 添加新的数据
            for (const QJsonValue &value : items)
            {
                if (value.isObject())
                {
                    QJsonObject obj = value.toObject();
                    YKItem item;
                    if (!point_address_list_.contains(obj["pointAddress"].toInt()))
                    {
                        point_address_list_.append(obj["pointAddress"].toInt());
                    }
                    item.commonAddress = obj["commonAddress"].toInt();
                    item.timestamp = obj["timestamp"].toVariant().toLongLong();
                    item.tieIdentificationIndex = obj["tieIdentificationIndex"].toInt();
                    item.tieIdentification = obj["tieIdentification"].toString();
                    item.causeIndex = obj["causeIndex"].toInt();
                    item.cause = obj["cause"].toString();
                    item.pointAddress = obj["pointAddress"].toInt();
                    item.value = obj["value"].toInt();
                    item.iv = obj["iv"].toInt();
                    item.direction = obj["direction"].toInt();
                    std::pair<QVector<YKItem>, QVector<YKItem>> &pair = point_address_group_[obj["pointAddress"].toInt()];
                    if (host == d5000_host)
                    {
                        pair.first.append(item);
                    }
                    else if (host == generation_host)
                    {
                        pair.second.append(item);
                    }
                }
            }
        }

        // 触发数据更新
        onDataUpdated();
    }

    if (method == "generate-check-report")
    {
        QString filePath = QFileDialog::getSaveFileName(this, tr("导出报告"), QDir::homePath() + "/比对报告.docx", tr("文本文件 (*.docx);;所有文件 (*.*)"));
        if (filePath.isEmpty())
        {
            return;
        }
        QFile file(filePath);
        if (!file.open(QIODevice::WriteOnly))
        {
            QMessageBox::warning(this, tr("导出失败"), tr("无法打开文件进行写入: %1").arg(file.errorString()));
            return;
        }
        // 将base64字符串转换为二进制数据
        QByteArray fileData = QByteArray::fromBase64(body.toUtf8());
        file.write(fileData);
        file.close();
        // 显示成功提示
        QMessageBox::information(this, "提示", "报告已生成");
    }
}

void YKComparison::onDataUpdated()
{
    // 1. 清理表格
    ui_->comparisonTable->clearContents();
    ui_->comparisonTable->setRowCount(0);

    // 获取当前选中的host
    QVariant d5000_item = ui_->d5000Combo->currentData();
    QVariant generation_item = ui_->generationCombo->currentData();

    if (d5000_item.isNull() || generation_item.isNull())
    {
        return;
    }

    int d5000_station_id = d5000_item.toMap()["id"].toInt();
    int generation_station_id = generation_item.toMap()["id"].toInt();

    // 计算表格行数
    int max_row_count = 0;
    for (int point_address : point_address_list_)
    {
        // 从d5000_items_和generation_items_中根据point_address找到对应的行数
        int d5000_row = 0;
        int generation_row = 0;
        std::pair<QVector<YKItem>, QVector<YKItem>> &pair = point_address_group_[point_address];
        for (int i = 0; i < pair.first.size(); i++)
        {
            if (pair.first[i].pointAddress == point_address)
            {
                d5000_row++;
            }
        }
        for (int i = 0; i < pair.second.size(); i++)
        {
            if (pair.second[i].pointAddress == point_address)
            {
                generation_row++;
            }
        }
        max_row_count += qMax(d5000_row, generation_row);
    }

    // 定义深/浅两种背景色根据点好进行切换
    QColor background_colors[2] = {QColor("#1E3153"), QColor("#3f72af")};
    int background_color_index = 0;
    for (int point_address : point_address_list_)
    {
        background_color_index = (background_color_index + 1) % 2;
        QColor current_background_color = background_colors[background_color_index];
        std::pair<QVector<YKItem>, QVector<YKItem>> &pair = point_address_group_[point_address];
        QVector<YKItem> &d5000_items = pair.first;
        QVector<YKItem> &generation_items = pair.second;

        // 开始遍历和并渲染
        for (int i = 0; i < qMax(d5000_items.size(), generation_items.size()); i++)
        {
            // 获取表格行数
            int row = ui_->comparisonTable->rowCount();
            ui_->comparisonTable->insertRow(row);
            // 填充完整列，默认值为空，设置背景色和字体居中
            for (int column = 0; column < ui_->comparisonTable->horizontalHeader()->count(); column++)
            {
                ui_->comparisonTable->setItem(row, column, new QTableWidgetItem(""));
                ui_->comparisonTable->item(row, column)->setBackground(current_background_color);
                ui_->comparisonTable->item(row, column)->setTextAlignment(Qt::AlignCenter);
            }

            // 第0列：序号
            ui_->comparisonTable->item(row, 0)->setText(QString::number(row + 1));

            // 第1列：状态比较
            QTableWidgetItem *status_item = ui_->comparisonTable->item(row, 1);
            status_item->setText("不一致");
            status_item->setForeground(QColor("#dd6161"));

            bool has_d5000 = i < d5000_items.size();
            bool has_generation = i < generation_items.size();

            if (has_d5000 && has_generation)
            {
                const YKItem &d5000_item = d5000_items[i];
                const YKItem &generation_item = generation_items[i];

                // 比较所有相关字段
                bool is_consistent =
                    d5000_item.commonAddress == generation_item.commonAddress &&
                    d5000_item.pointAddress == generation_item.pointAddress &&
                    d5000_item.tieIdentificationIndex == generation_item.tieIdentificationIndex &&
                    d5000_item.value == generation_item.value &&
                    d5000_item.iv == generation_item.iv &&
                    d5000_item.causeIndex == generation_item.causeIndex;
                if (is_consistent)
                {
                    status_item->setText("一致");
                    status_item->setForeground(QColor("#67C23A"));
                }
            }

            // 渲染 d5000 数据（第2-9列）
            if (has_d5000)
            {
                const YKItem &item = d5000_items[i];
                QTableWidgetItem *table_item = ui_->comparisonTable->item(row, 0);
                table_item->setData(Qt::UserRole + 1, QVariant::fromValue(item));

                QString point_desc = DatabaseManager::queryPointDesc(d5000_station_id, item.pointAddress);
                ui_->comparisonTable->item(row, 2)->setText(point_desc);
                ui_->comparisonTable->item(row, 3)->setText(QString::number(item.commonAddress));
                ui_->comparisonTable->item(row, 4)->setText(QString::number(item.pointAddress));
                ui_->comparisonTable->item(row, 5)->setText(item.direction == 0 ? "上行" : "下行");
                ui_->comparisonTable->item(row, 6)->setText(QDateTime::fromMSecsSinceEpoch(item.timestamp).toString("yyyy-MM-dd HH:mm:ss.zzz"));
                ui_->comparisonTable->item(row, 7)->setText(item.tieIdentification);
                QString valueText = "--";
                if (item.tieIdentificationIndex == 45 || item.tieIdentificationIndex == 58)
                {
                    if (item.value == 0)
                    {
                        valueText = "分";
                    }
                    else if (item.value == 1)
                    {
                        valueText = "合";
                    }
                }
                else if (item.tieIdentificationIndex == 46 || item.tieIdentificationIndex == 59)
                {
                    if (item.value == 1)
                    {
                        valueText = "分";
                    }
                    else if (item.value == 2)
                    {
                        valueText = "合";
                    }
                }
                ui_->comparisonTable->item(row, 8)->setText(valueText);
                QString causeText = "--";
                if (item.causeIndex == 6 && item.iv == 0)
                {
                    causeText = "遥控执行帧";
                }
                if (item.causeIndex == 6 && item.iv == 1)
                {
                    causeText = "遥控选择帧";
                }
                if (item.causeIndex == 7 && item.iv == 0)
                {
                    causeText = "遥控执行确认正确帧";
                }
                if (item.causeIndex == 7 && item.iv == 1)
                {
                    causeText = "遥控选择返校正确帧";
                }
                if (item.causeIndex == 8 && item.iv == 1)
                {
                    causeText = "遥控撤销帧";
                }
                if (item.causeIndex == 9 && item.iv == 1)
                {
                    causeText = "遥控撤销确认帧";
                }
                if (item.causeIndex == 10 && item.iv == 0)
                {
                    causeText = "遥控命令结束帧";
                }
                ui_->comparisonTable->item(row, 9)->setText(causeText);
            }

            // 渲染新一代数据（第2列和第10-16列）
            if (has_generation)
            {
                const YKItem &item = generation_items[i];
                QTableWidgetItem *table_item = ui_->comparisonTable->item(row, 0);
                table_item->setData(Qt::UserRole + 2, QVariant::fromValue(item));
                QString point_desc = DatabaseManager::queryPointDesc(generation_station_id, item.pointAddress);
                ui_->comparisonTable->item(row, 2)->setText(point_desc);
                ui_->comparisonTable->item(row, 10)->setText(QString::number(item.commonAddress));
                ui_->comparisonTable->item(row, 11)->setText(QString::number(item.pointAddress));
                ui_->comparisonTable->item(row, 12)->setText(item.direction == 0 ? "上行" : "下行");
                ui_->comparisonTable->item(row, 13)->setText(QDateTime::fromMSecsSinceEpoch(item.timestamp).toString("yyyy-MM-dd HH:mm:ss.zzz"));
                ui_->comparisonTable->item(row, 14)->setText(item.tieIdentification);
                QString valueText2 = "--";
                if (item.tieIdentificationIndex == 45 || item.tieIdentificationIndex == 58)
                {
                    if (item.value == 0)
                    {
                        valueText2 = "分";
                    }
                    else if (item.value == 1)
                    {
                        valueText2 = "合";
                    }
                }
                else if (item.tieIdentificationIndex == 46 || item.tieIdentificationIndex == 59)
                {
                    if (item.value == 1)
                    {
                        valueText2 = "分";
                    }
                    else if (item.value == 2)
                    {
                        valueText2 = "合";
                    }
                }
                ui_->comparisonTable->item(row, 15)->setText(valueText2);
                QString causeText = "--";
                if (item.causeIndex == 6 && item.iv == 0)
                {
                    causeText = "遥控执行帧";
                }
                if (item.causeIndex == 6 && item.iv == 1)
                {
                    causeText = "遥控选择帧";
                }
                if (item.causeIndex == 7 && item.iv == 0)
                {
                    causeText = "遥控执行确认正确帧";
                }
                if (item.causeIndex == 7 && item.iv == 1)
                {
                    causeText = "遥控选择返校正确帧";
                }
                if (item.causeIndex == 8 && item.iv == 1)
                {
                    causeText = "遥控撤销帧";
                }
                if (item.causeIndex == 9 && item.iv == 1)
                {
                    causeText = "遥控撤销确认帧";
                }
                if (item.causeIndex == 10 && item.iv == 0)
                {
                    causeText = "遥控命令结束帧";
                }
                ui_->comparisonTable->item(row, 16)->setText(causeText);
            }
        }
    }
}

void YKComparison::onTableItemClicked(int row, int column)
{
    // 选中整行
    ui_->comparisonTable->selectRow(row);

    // 调用渲染TED内容的函数
    renderTEDContent(row);
}

void YKComparison::renderTEDContent(int row)
{
    // 清空TED内容
    ui_->d5000TED->clear();
    ui_->generationTED->clear();

    // 获取表格的列标题
    QStringList headers;
    for (int i = 0; i < ui_->comparisonTable->columnCount(); i++)
    {
        headers.append(ui_->comparisonTable->horizontalHeaderItem(i)->text());
    }

    // D5000的参数详情
    QStringList d5000_lines;
    // 新一代的参数详情
    QStringList generation_lines;

    // 获取d5000_items的数据
    if (ui_->comparisonTable->item(row, 0)->data(Qt::UserRole + 1).isValid())
    {
        YKItem item = ui_->comparisonTable->item(row, 0)->data(Qt::UserRole + 1).value<YKItem>();

        // 添加公共地址
        d5000_lines << QString("%1: %2").arg(headers[3]).arg(item.commonAddress);
        // 添加点号
        d5000_lines << QString("%1: %2").arg(headers[4]).arg(item.pointAddress);
        // 添加方向
        d5000_lines << QString("%1: %2").arg(headers[5]).arg(item.direction == 0 ? "上行" : "下行");
        // 添加类型
        d5000_lines << QString("%1: %2").arg(headers[7]).arg(item.tieIdentification);
        // 添加目标值
        d5000_lines << QString("%1: %2").arg(headers[8]).arg(item.value);
        // 添加原因
        d5000_lines << QString("%1: %2/%3(%4)").arg(headers[9]).arg(item.causeIndex).arg(item.iv).arg(item.cause);
    }

    // 获取generation_items的数据
    if (ui_->comparisonTable->item(row, 0)->data(Qt::UserRole + 2).isValid())
    {
        YKItem item = ui_->comparisonTable->item(row, 0)->data(Qt::UserRole + 2).value<YKItem>();

        // 添加公共地址
        generation_lines << QString("%1: %2").arg(headers[10]).arg(item.commonAddress);
        // 添加点号
        generation_lines << QString("%1: %2").arg(headers[11]).arg(item.pointAddress);
        // 添加方向
        generation_lines << QString("%1: %2").arg(headers[12]).arg(item.direction == 0 ? "上行" : "下行");
        // 添加类型
        generation_lines << QString("%1: %2").arg(headers[14]).arg(item.tieIdentification);
        // 添加目标值
        generation_lines << QString("%1: %2").arg(headers[15]).arg(item.value);
        // 添加原因
        generation_lines << QString("%1: %2/%3(%4)").arg(headers[16]).arg(item.causeIndex).arg(item.iv).arg(item.cause);
    }

    // 构建带颜色的HTML文本
    QString d5000_html;
    QString generation_html;

    // 对每一行进行比较和着色
    for (int i = 0; i < qMax(d5000_lines.size(), generation_lines.size()); i++)
    {
        bool is_different = false;
        if (i < d5000_lines.size() && i < generation_lines.size())
        {
            is_different = d5000_lines[i] != generation_lines[i];
        }
        else
        {
            is_different = true;
        }

        // 添加D5000的行
        if (i < d5000_lines.size())
        {
            if (is_different)
            {
                d5000_html += QString("<span style='color: #dd6161;'>%1</span><br>").arg(d5000_lines[i]);
            }
            else
            {
                d5000_html += QString("%1<br>").arg(d5000_lines[i]);
            }
        }

        // 添加新一代的行
        if (i < generation_lines.size())
        {
            if (is_different)
            {
                generation_html += QString("<span style='color: #dd6161;'>%1</span><br>").arg(generation_lines[i]);
            }
            else
            {
                generation_html += QString("%1<br>").arg(generation_lines[i]);
            }
        }
    }

    // 设置HTML文本到QTextEdit
    ui_->d5000TED->setHtml(d5000_html);
    ui_->generationTED->setHtml(generation_html);
}

void YKComparison::on_exportBtn_clicked()
{

    QTableWidget *table = ui_->comparisonTable;
    const int rowCount = table->rowCount();
    const int colCount = table->columnCount();
    QJsonArray jsonData;
    // 添加HEADER
    QJsonArray headerRow;
    for (int col = 0; col < colCount; ++col)
    {
        // 获取表头项，处理空指针
        if (QTableWidgetItem *headerItem = table->horizontalHeaderItem(col))
        {
            headerRow.append(headerItem->text());
        }
        else
        {
            headerRow.append(""); // 空表头用空字符串占位
        }
    }
    jsonData.append(headerRow);
    // 添加DATA
    for (int row = 0; row < rowCount; ++row)
    {
        QJsonArray rowData;

        // 遍历每一列
        for (int col = 0; col < colCount; ++col)
        {
            // 获取单元格内容，处理空指针
            if (QTableWidgetItem *item = table->item(row, col))
            {
                rowData.append(item->text());
            }
            else
            {
                rowData.append(""); // 空单元格用空字符串占位
            }
        }

        jsonData.append(rowData);
    }

    // 转换为JSON字符串
    QJsonDocument doc(jsonData);
    QString jsonString = doc.toJson(QJsonDocument::Compact);
    dealer_handler_->sendRequest("generate-check-report", jsonString);
}
